package org.jks.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jks.constant.Constants;
import org.jks.constant.SysError;
import org.jks.model.User;
import org.jks.response.model.ActionResult;
import org.jks.util.PrivilegeUtil;
import org.jks.util.ResponseUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class PrivilegeInterceptor implements HandlerInterceptor{

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Constants.SESSION_ACCOUNT);
		int ret = SysError.FAILURE;
		String action = request.getRequestURI();
		if(user != null){
			ret = PrivilegeUtil.hasPrivlege(session, action);
		}
		if(ret == SysError.ERR_NO_CHECK){
			return true;
		}
		ActionResult ar = new ActionResult();
		if(ret == SysError.ERR_NO_PRIVILEGE ){
			ar.setMsg("您没有权限，请联系管理员");
			ResponseUtil.returnJson(response, ar);
			return false;
		}
		else if(ret == SysError.ERR_NOT_LOGIN){
			ar.setMsg("您没登录，请先登录");
			ResponseUtil.returnJson(response, ar);
			return false;
		}
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	

}
